from PyQt5.QtWidgets import (QApplication, QMessageBox, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, 
                             QGroupBox, QCheckBox, QLabel, QLineEdit, QTextEdit, 
                             QPushButton, QFileDialog, QListWidget, QComboBox, 
                             QDateTimeEdit, QTabWidget, QStatusBar, QDialog, QDialogButtonBox)
from PyQt5.QtCore import Qt, QDateTime
import sys
import time
from pathlib import Path
import asyncio
from datetime import datetime, timedelta
from pathlib import Path
from PyQt5.QtCore import pyqtSignal, QObject
from uploader.douyin_uploader.main import DouYinVideo
from utils.files_times import get_title_and_hashtags
from conf import BASE_DIR
from uploader.tencent_uploader.main import TencentVideo, weixin_setup
from utils.constant import TencentZoneTypes
from uploader.ks_uploader.main import KSVideo
# 从枚举文件中导入
from utils.constant import VideoZoneTypes, TencentZoneTypes
from uploader.bilibili_uploader.raw_main import (
    read_cookie_json_file,
    extract_keys_from_json,
    random_emoji,
    BilibiliUploader
)
from utils.files_times import get_title_and_hashtags
from conf import BASE_DIR

import asyncio
from PyQt5.QtCore import QObject, pyqtSignal

class AsyncRunner(QObject):
    finished = pyqtSignal(object)  # 用于返回执行结果
    
    def __init__(self):
        super().__init__()
        self.loop = asyncio.new_event_loop()
        
    def run_async(self, coro):
        """在后台线程中运行异步代码"""
        def wrapper():
            try:
                result = self.loop.run_until_complete(coro)
                self.finished.emit(result)
            except Exception as e:
                self.finished.emit(e)
        
        asyncio.set_event_loop(self.loop)
        self.loop.run_in_executor(None, wrapper)

class VideoPublisherGUI(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("多平台视频发布工具")
        self.setGeometry(100, 100, 800, 600)
   
        self.init_ui()
        
    def init_ui(self):
        # 主布局
        main_widget = QWidget()
        self.setCentralWidget(main_widget)
        main_layout = QVBoxLayout()
        main_widget.setLayout(main_layout)
        
        # 平台选择区域
        platform_group = QGroupBox("选择发布平台")
        platform_layout = QHBoxLayout()
        
        self.bilibili_cb = QCheckBox("哔哩哔哩")
        self.douyin_cb = QCheckBox("抖音")
        self.kuaishou_cb = QCheckBox("快手")
        self.weixin_cb = QCheckBox("微信视频号")
        
        platform_layout.addWidget(self.bilibili_cb)
        platform_layout.addWidget(self.douyin_cb)
        platform_layout.addWidget(self.kuaishou_cb)
        platform_layout.addWidget(self.weixin_cb)
        platform_group.setLayout(platform_layout)
        main_layout.addWidget(platform_group)
        
        # 视频选择区域
        video_group = QGroupBox("视频选择")
        video_layout = QVBoxLayout()
        
        self.video_list = QListWidget()
        self.video_list.itemDoubleClicked.connect(self.edit_video_meta)
        
        btn_layout = QHBoxLayout()
        add_video_btn = QPushButton("添加视频")
        add_video_btn.clicked.connect(self.add_videos)
        edit_meta_btn = QPushButton("编辑标题/标签")
        edit_meta_btn.clicked.connect(self.edit_video_meta)
        video_layout.addWidget(add_video_btn)
        btn_layout.addWidget(edit_meta_btn)
        
        video_layout.addWidget(self.video_list)
        video_layout.addLayout(btn_layout)
        video_group.setLayout(video_layout)
        main_layout.addWidget(video_group)
        
        # 添加视频元数据存储
        self.video_metas = {}  # 格式: {文件路径: {"title": "", "tags": []}}
        
        # 发布设置区域 (使用标签页)
        settings_tabs = QTabWidget()
        
        # 通用设置
        general_tab = QWidget()
        general_layout = QVBoxLayout()

        # 发布时间
        time_layout = QHBoxLayout()
        time_layout.addWidget(QLabel("发布时间:"))
        self.time_edit = QDateTimeEdit()
        self.time_edit.setDateTime(QDateTime.currentDateTime())
        self.time_edit.setDisplayFormat("yyyy-MM-dd HH:mm:ss")
        self.immediate_cb = QCheckBox("立即发布")
        self.immediate_cb.stateChanged.connect(self.toggle_time_edit)
        
        time_layout.addWidget(self.time_edit)
        time_layout.addWidget(self.immediate_cb)
        general_layout.addLayout(time_layout)
        
        general_tab.setLayout(general_layout)
        settings_tabs.addTab(general_tab, "通用设置")
        
        # 平台特定设置
        self.platform_tabs = {}
        
        # B站设置
        bilibili_tab = QWidget()
        bilibili_layout = QVBoxLayout()
        
        zone_layout = QHBoxLayout()
        zone_layout.addWidget(QLabel("分区:"))
        self.bilibili_zone_combo = QComboBox()

        #self.bilibili_zone_combo.addItems(["体育-足球", "生活", "科技", "游戏","舞蹈","音乐","影视","知识"])
        #zone_layout.addWidget(self.bilibili_zone_combo)
        bilibili_layout.addLayout(zone_layout)
        
        bilibili_tab.setLayout(bilibili_layout)
        settings_tabs.addTab(bilibili_tab, "哔哩哔哩设置")
        self.platform_tabs["bilibili"] = bilibili_tab
        
        # 抖音设置
        douyin_tab = QWidget()
        douyin_layout = QVBoxLayout()
        # 可以添加抖音特定设置
        douyin_tab.setLayout(douyin_layout)
        settings_tabs.addTab(douyin_tab, "抖音设置")
        self.platform_tabs["douyin"] = douyin_tab
        
        # 快手设置
        kuaishou_tab = QWidget()
        kuaishou_layout = QVBoxLayout()
        # 可以添加快手特定设置
        kuaishou_tab.setLayout(kuaishou_layout)
        settings_tabs.addTab(kuaishou_tab, "快手设置")
        self.platform_tabs["kuaishou"] = kuaishou_tab
        
        # 微信视频号设置
        weixin_tab = QWidget()
        weixin_layout = QVBoxLayout()
        
        category_layout = QHBoxLayout()
        category_layout.addWidget(QLabel("分类:"))
        self.weixin_category_combo = QComboBox()
        # 添加微信视频号分类选项
        #self.weixin_category_combo.addItems(["生活", "科技", "体育", "娱乐"])
        category_layout.addWidget(self.weixin_category_combo)
        weixin_layout.addLayout(category_layout)
        
        weixin_tab.setLayout(weixin_layout)
        settings_tabs.addTab(weixin_tab, "微信视频号设置")
        self.platform_tabs["weixin"] = weixin_tab
        
        main_layout.addWidget(settings_tabs)
        
        # 发布按钮
        publish_btn = QPushButton("发布视频")
        publish_btn.clicked.connect(self.publish_videos)
        main_layout.addWidget(publish_btn)
        
        # 状态栏
        self.status_bar = QStatusBar()
        self.setStatusBar(self.status_bar)
        
        # 连接平台选择信号
        self.bilibili_cb.stateChanged.connect(lambda: self.toggle_platform_tab("bilibili"))
        self.douyin_cb.stateChanged.connect(lambda: self.toggle_platform_tab("douyin"))
        self.kuaishou_cb.stateChanged.connect(lambda: self.toggle_platform_tab("kuaishou"))
        self.weixin_cb.stateChanged.connect(lambda: self.toggle_platform_tab("weixin"))
    def init_bilibili_zone_combo(self):
        #初始化B站分区下拉框"""
        zone_options = [
            ("体育-足球", VideoZoneTypes.SPORTS_FOOTBALL),
            ("生活", VideoZoneTypes.LIFE),
            ("科技", VideoZoneTypes.TECH),
            ("游戏", VideoZoneTypes.GAME),
            ("舞蹈", VideoZoneTypes.DANCE),
            ("音乐", VideoZoneTypes.MUSIC),
            ("影视", VideoZoneTypes.CINEPHILE),
            ("知识", VideoZoneTypes.KNOWLEDGE),
            ("美食", VideoZoneTypes.FOOD),
            ("动物圈", VideoZoneTypes.ANIMAL),
            ("时尚", VideoZoneTypes.FASHION),
            ("VLOG", VideoZoneTypes.VLOG)
        ]
        
        self.bilibili_zone_combo.clear()
        for zone_name, _ in zone_options:
            self.bilibili_zone_combo.addItem(zone_name)
        
        # 默认选择体育-足球
        self.bilibili_zone_combo.setCurrentText("体育-足球")
    def toggle_time_edit(self, state):
        self.time_edit.setEnabled(state != Qt.Checked)
        
    def toggle_platform_tab(self, platform):
        # 根据平台选择显示/隐藏对应的设置标签页
        pass
        
    def add_videos(self):
        files, _ = QFileDialog.getOpenFileNames(
            self, "选择视频文件", "", "视频文件 (*.mp4 *.avi *.mov)")
        if files:
            for file in files:
                self.video_list.addItem(file)
                # 初始化元数据
                title, tags = get_title_and_hashtags(file)
                self.video_metas[file] = {
                    "title": title,
                    "tags": tags
                }
    def edit_video_meta(self):
        #编辑选中视频的标题和标签"""
        selected_items = self.video_list.selectedItems()
        if not selected_items:
            QMessageBox.warning(self, "警告", "请先选择一个视频")
            return
            
        file_path = selected_items[0].text()
        meta = self.video_metas.get(file_path, {"title": "", "tags": []})
        
        # 创建编辑对话框
        dialog = QDialog(self)
        dialog.setWindowTitle("编辑视频信息")
        layout = QVBoxLayout()
        
        # 标题编辑
        title_layout = QHBoxLayout()
        title_layout.addWidget(QLabel("标题:"))
        title_edit = QLineEdit(meta["title"])
        title_layout.addWidget(title_edit)
        layout.addLayout(title_layout)
        
        # 标签编辑
        tags_layout = QHBoxLayout()
        tags_layout.addWidget(QLabel("标签(用逗号分隔):"))
        tags_edit = QLineEdit(",".join(meta["tags"]))
        tags_layout.addWidget(tags_edit)
        layout.addLayout(tags_layout)
        
        # 确认按钮
        btn_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        btn_box.accepted.connect(dialog.accept)
        btn_box.rejected.connect(dialog.reject)
        layout.addWidget(btn_box)
        
        dialog.setLayout(layout)
        
        if dialog.exec_() == QDialog.Accepted:
            # 保存修改
            self.video_metas[file_path] = {
                "title": title_edit.text(),
                "tags": [tag.strip() for tag in tags_edit.text().split(",") if tag.strip()]
            }
            
    def publish_videos(self):
        # 获取选中的平台
        platforms = []
        if self.bilibili_cb.isChecked(): platforms.append("bilibili")
        if self.douyin_cb.isChecked(): platforms.append("douyin")
        if self.kuaishou_cb.isChecked(): platforms.append("kuaishou")
        if self.weixin_cb.isChecked(): platforms.append("weixin")
        
        if not platforms:
            self.status_bar.showMessage("请至少选择一个发布平台！", 5000)
            return
            
        # 获取视频文件和对应的元数据
        video_metas = []
        for i in range(self.video_list.count()):
            file_path = self.video_list.item(i).text()
            meta = self.video_metas.get(file_path, {"title": "", "tags": []})
            video_metas.append({
                "file": file_path,
                "title": meta["title"],
                "tags": meta["tags"]
            })
        
            
        # 获取视频文件
        if not video_metas:
            self.status_bar.showMessage("请添加至少一个视频文件！", 5000)
            return
            
        # 获取发布设置
        immediate = self.immediate_cb.isChecked()
        publish_time = self.time_edit.dateTime().toString("yyyy-MM-dd HH:mm:ss") if not immediate else None
        
        # 获取平台特定设置
        bilibili_zone = self.bilibili_zone_combo.currentText() if "bilibili" in platforms else None
        weixin_category = self.weixin_category_combo.currentText() if "weixin" in platforms else None
        
        # 调用各平台发布逻辑
        self.status_bar.showMessage("开始发布视频...")
        
 
        # 获取视频文件和对应的元数据
        video_metas = []
        for i in range(self.video_list.count()):
            file_path = self.video_list.item(i).text()
            meta = self.video_metas.get(file_path, {"title": "", "tags": []})
            video_metas.append({
                "file": file_path,
                "title": meta["title"],
                "tags": meta["tags"]
            })
        
        if not video_metas:
            self.status_bar.showMessage("请添加至少一个视频文件！", 5000)
            return
            
        # 获取发布设置
        immediate = self.immediate_cb.isChecked()
        publish_time = self.time_edit.dateTime().toString("yyyy-MM-dd HH:mm:ss") if not immediate else None
        
        # 获取平台特定设置
        bilibili_zone = self.bilibili_zone_combo.currentText() if "bilibili" in platforms else None
        weixin_category = self.weixin_category_combo.currentText() if "weixin" in platforms else None
        
        # 调用各平台发布逻辑
        self.status_bar.showMessage("开始发布视频...")
        
        # 这里应该调用您现有的发布逻辑，根据平台选择调用不同的发布函数
        # 例如：
  
        if "bilibili" in platforms:
            self.publish_to_bilibili(video_metas, publish_time, bilibili_zone)
            
        if "douyin" in platforms:
            self.publish_to_douyin(video_metas, publish_time)
            
        if "kuaishou" in platforms:
            self.publish_to_kuaishou(video_metas, publish_time)
            
        if "weixin" in platforms:
            self.publish_to_weixin(video_metas, publish_time)
    # 类似处理其他平台...
    def publish_to_bilibili(self, video_metas, publish_time, zone):
        #发布视频到B站"""
        try:
            # 转换分区名称到对应的VideoZoneTypes枚举值
            zone_mapping = {
                "体育-足球": VideoZoneTypes.SPORTS_FOOTBALL,
                "生活": VideoZoneTypes.LIFE,
                "科技": VideoZoneTypes.TECH,
                "游戏": VideoZoneTypes.GAME,
                "舞蹈": VideoZoneTypes.DANCE,
                "音乐": VideoZoneTypes.MUSIC,
                "影视": VideoZoneTypes.CINEPHILE,
                "知识": VideoZoneTypes.KNOWLEDGE,
                "美食": VideoZoneTypes.FOOD,
                "动物圈": VideoZoneTypes.ANIMAL,
                "时尚": VideoZoneTypes.FASHION,
                "VLOG": VideoZoneTypes.VLOG
            }
            
            # 获取分区枚举值
            zone_enum = zone_mapping.get(zone, VideoZoneTypes.SPORTS_FOOTBALL)
            tid = zone_enum.value  # 获取分区ID
            
            # 获取账号配置
            account_file = Path(BASE_DIR) / "cookies" / "bilibili_uploader" / "account.json"
            if not account_file.exists():
                QMessageBox.critical(self, "错误", "B站账号配置文件不存在！")
                return False
                
            # 读取cookie
            cookie_data = read_cookie_json_file(account_file)
            cookie_data = extract_keys_from_json(cookie_data)
            
            # 处理发布时间
            if publish_time:
                # 定时发布
                publish_dt = QDateTime.fromString(publish_time, "yyyy-MM-dd HH:mm:ss")
                timestamp = int(publish_dt.toSecsSinceEpoch())
                if timestamp - int(time.time())<14400:
                    timestamp = int(time.time()+14500)
            else:
                # 立即发布
                timestamp = 0
            
            # 遍历视频文件
            success_count = 0
            for index, meta in enumerate(video_metas):
                file_path = meta["file"]
                title = meta["title"]
                tags_list = meta["tags"]
                
                file = Path(file_path)
                if not file.exists():
                    QMessageBox.warning(self, "警告", f"视频文件不存在: {file_path}")
                    continue
              
                # 确保标签是字符串列表
                tags_list = [str(tag) for tag in tags_list]
                tags_str = ','.join(tags_list)
                desc = title + random_emoji() # 描述使用和标题相同
                
                # 更新状态
                self.status_bar.showMessage(f"正在上传到B站: {file.name}...")
                QApplication.processEvents()  # 强制刷新UI
                print("发布时间")
                print(datetime.fromtimestamp(timestamp))
                try:
                    # 创建上传器并上传
                    bili_uploader = BilibiliUploader(
                        cookie_data,
                        file,
                        title,
                        desc,
                        tid,
                        tags_list,  # 使用处理后的标签列表
                        timestamp
                    )
                    
                    # 执行上传
                    result = bili_uploader.upload()
                    
                    if result:
                        success_count += 1
                        self.status_bar.showMessage(f"成功上传到B站: {file.name}", 5000)
                        self.add_to_history(
                            platform="bilibili",
                            filename=file.name,
                            title=title,
                            tags=tags_str,
                            publish_time=publish_time if publish_time else "立即发布"
                        )
                    else:
                        QMessageBox.warning(self, "上传失败", f"上传到B站失败: {file.name}")
                    
                except Exception as e:
                    QMessageBox.critical(self, "上传错误", f"B站上传出错: {str(e)}")
                    continue
                    
            # 显示最终结果
            if success_count > 0:
                #QMessageBox.information(
                #    self, 
                #    "上传完成", 
                #    f"成功上传 {success_count}/{len(video_metas)} 个视频到B站"
                #)
                self.status_bar.showMessage(f"成功上传 {success_count}/{len(video_metas)} 个视频到B站")
                return True
            else:
                QMessageBox.warning(self, "上传失败", "所有视频上传到B站均失败")
                return False
                
        except Exception as e:
            QMessageBox.critical(self, "初始化错误", f"B站发布初始化失败: {str(e)}")
            return False
    def add_to_history(self, platform, filename, title, tags, publish_time):
        #添加到发布历史记录"""
        if not hasattr(self, 'publish_history'):
            self.publish_history = []
            
        history_entry = {
            'platform': platform,
            'filename': filename,
            'title': title,
            'tags': tags,
            'time': publish_time,
            'status': '成功',
            'timestamp': datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        }
        
        self.publish_history.append(history_entry)
        
        # 如果需要保存到文件
        history_file = Path(BASE_DIR) / "publish_history.json"
        try:
            import json
            with open(history_file, 'a', encoding='utf-8') as f:
                f.write(json.dumps(history_entry, ensure_ascii=False) + "\n")
        except Exception as e:
            print(f"保存历史记录失败: {str(e)}")

    def publish_to_douyin(self, video_metas, publish_time):
        #同步版本的抖音发布方法"""
        try:
            # 获取账号配置
            account_file = Path(BASE_DIR) / "cookies" / "douyin_uploader" / "account.json"
            if not account_file.exists():
                QMessageBox.critical(self, "错误", "抖音账号配置文件不存在！")
                return False
                
            # 处理发布时间 定时发布
            if publish_time:
                publish_dt = datetime.strptime(publish_time, "%Y-%m-%d %H:%M:%S")
            else: # 立即发布
                publish_dt = 0
            print("发布时间")
            print(publish_dt)
            success_count = 0
            for index, meta in enumerate(video_metas):
                file_path = meta["file"]
                title = meta["title"]
                tags_list = meta["tags"]
                
                file = Path(file_path)
                if not file.exists():
                    QMessageBox.warning(self, "警告", f"视频文件不存在: {file_path}")
                    continue
                    
                # 计算实际发布时间（多个视频间隔1分钟）
                current_publish_time = publish_dt
                
                # 更新状态
                self.status_bar.showMessage(f"正在上传到抖音: {file.name}...")
                QApplication.processEvents()  # 刷新UI
                
                try:
                    # 创建发布实例
                    app = DouYinVideo(
                        title,
                        file,
                        tags_list,
                        current_publish_time,
                        account_file
                    )
                    
                    # 执行同步发布
                    asyncio.run(app.main(), debug=False)
                    success_count += 1
                    self.add_to_history(
                        platform="douyin",
                        filename=file.name,
                        title=title,
                        tags=",".join(tags_list),
                        publish_time=current_publish_time.strftime("%Y-%m-%d %H:%M:%S") if publish_time else "立即发布"
                    )
                    
                except Exception as e:
                    QMessageBox.critical(self, "上传错误", f"抖音上传出错: {str(e)}")
                    continue
                    
            # 显示最终结果
            if success_count > 0:
                #QMessageBox.information(
                #    self, 
                #    "上传完成", 
                #    f"成功上传 {success_count}/{len(video_metas)} 个视频到抖音"
                #)
                self.status_bar.showMessage(f"成功上传 {success_count}/{len(video_metas)} 个视频到抖音")
                return True
            else:
                QMessageBox.warning(self, "上传失败", "所有视频上传到抖音均失败")
                return False
                
        except Exception as e:
            QMessageBox.critical(self, "错误", f"抖音发布失败: {str(e)}")
            return False
            
    def publish_to_kuaishou(self, video_metas, publish_time):
        #同步版本的快手发布方法"""
        try:
            # 获取账号配置
            account_file = Path(BASE_DIR) / "cookies" / "ks_uploader" / "account.json"
            if not account_file.exists():
                QMessageBox.critical(self, "错误", "快手账号配置文件不存在！")
                return False
                
            # 处理发布时间
            if publish_time:
                publish_dt = datetime.strptime(publish_time, "%Y-%m-%d %H:%M:%S")
            else:
                publish_dt = 0
            
            success_count = 0
            for index, meta in enumerate(video_metas):
                file_path = meta["file"]
                title = meta["title"]
                tags_list = meta["tags"]
                
                file = Path(file_path)
                if not file.exists():
                    QMessageBox.warning(self, "警告", f"视频文件不存在: {file_path}")
                    continue
                
                # 更新状态
                self.status_bar.showMessage(f"正在上传到快手: {file.name}...")
                QApplication.processEvents()  # 刷新UI
                
                try:
                    # 创建发布实例
                    app = KSVideo(
                        title,
                        file,
                        tags_list,
                        publish_dt,
                        account_file
                    )
             
                    # 执行同步发布
                    asyncio.run(app.main(), debug=False)
                    success_count += 1
                    self.add_to_history(
                        platform="kuaishou",
                        filename=file.name,
                        title=title,
                        tags=",".join(tags_list),
                        publish_time=publish_dt.strftime("%Y-%m-%d %H:%M:%S") if publish_time else "立即发布"
                    )
                    
                except Exception as e:
                    QMessageBox.critical(self, "上传错误", f"快手上传出错: {str(e)}")
                    continue
                    
            # 显示最终结果
            if success_count > 0:
                #QMessageBox.information(
                #    self, 
                #    "上传完成", 
                #    f"成功上传 {success_count}/{len(video_metas)} 个视频到快手"
                #)
                self.status_bar.showMessage(f"成功上传 {success_count}/{len(video_metas)} 个视频到快手")
                return True
            else:
                QMessageBox.warning(self, "上传失败", "所有视频上传到快手均失败")
                return False
                
        except Exception as e:
            QMessageBox.critical(self, "错误", f"快手发布失败: {str(e)}")
            return False
            
    def publish_to_weixin(self, video_metas, publish_time):
        #同步版本的微信视频号发布方法"""
        try:
            # 获取账号配置
            account_file = Path(BASE_DIR) / "cookies" / "tencent_uploader" / "account.json"
            if not account_file.exists():
                QMessageBox.critical(self, "错误", "微信视频号账号配置文件不存在！")
                return False
                
            # 处理发布时间
            if publish_time:
                publish_dt = datetime.strptime(publish_time, "%Y-%m-%d %H:%M:%S")
            else:
                publish_dt = 0
            
            success_count = 0
            for index, meta in enumerate(video_metas):
                file_path = meta["file"]
                title = meta["title"]
                tags_list = meta["tags"]
                
                file = Path(file_path)
                if not file.exists():
                    QMessageBox.warning(self, "警告", f"视频文件不存在: {file_path}")
                    continue

                # 更新状态
                self.status_bar.showMessage(f"正在上传到微信视频号: {file.name}...")
                QApplication.processEvents()  # 刷新UI
                # todo
                category = TencentZoneTypes.LIFESTYLE.value  # 标记原创需要否则不需要传
                
                try:
                    # 创建发布实例
                    app = TencentVideo(
                        title,
                        file,
                        tags_list,
                        publish_dt,
                        account_file,
                        category
                    )
                    
                    # 执行同步发布
                    asyncio.run(app.main(), debug=False)
                    
                    success_count += 1
                    self.add_to_history(
                        platform="shipinhao",
                        filename=file.name,
                        title=title,
                        tags=",".join(tags_list),
                        publish_time=publish_dt.strftime("%Y-%m-%d %H:%M:%S") if publish_time else "立即发布"
                    )
                except Exception as e:
                    QMessageBox.critical(self, "上传错误", f"微信视频号上传出错: {str(e)}")
                    continue
                    
            # 显示最终结果
            if success_count > 0:
                #QMessageBox.information(
                #    self, 
                #    "上传完成", 
                #    f"成功上传 {success_count}/{len(video_metas)} 个视频到微信视频号"
                #)
                self.status_bar.showMessage(f"成功上传 {success_count}/{len(video_metas)} 个视频到微信视频号")
                self.status_bar.showMessage("success")
                return True
            else:
                QMessageBox.warning(self, "上传失败", "所有视频上传到微信视频号均失败")
                self.status_bar.showMessage("error")
                return False
                
        except Exception as e:
            QMessageBox.critical(self, "错误", f"微信视频号发布失败: {str(e)}")
            self.status_bar.showMessage("error")
            return False
        
    # 类似方法处理其他平台...

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = VideoPublisherGUI()
    window.show()
    sys.exit(app.exec_())